package com.luyuan.crm.member.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.event.authentication.AuthenticationSuccessEvent;
import org.springframework.security.userdetails.UserDetails;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.member.service.OnlineMemberService;
import com.ruijie.components.security.model.AppUser;

public class AopLogin implements ApplicationListener {

    private static final Log logger = LogFactory.getLog(AopLogin.class);

    private OnlineMemberService onlineService;

    private MemberService memberService;

    public void setOnlineService(OnlineMemberService onlineService) {
        this.onlineService = onlineService;
    }

    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof AuthenticationSuccessEvent) {
            AuthenticationSuccessEvent authEvent = (AuthenticationSuccessEvent) event;
            UserDetails user = (UserDetails) authEvent.getAuthentication().getPrincipal();
            // UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authEvent.getSource();
            // WebAuthenticationDetails detai = (WebAuthenticationDetails) token.getDetails();

            Member member = memberService.getByAccount((AppUser) user);
            if (member != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("模拟输出用户登录日志:[" + java.util.Calendar.getInstance().getTime() + "] "
                            + user.getUsername());
                }
                onlineService.onlineMember(member);
            }
        }

    }
}